package com.ycy.temperature.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.ycy.temperature.R;
import com.ycy.temperature.date.net.UserNetWorks;
import com.ycy.temperature.date.utils.GlideImageLoader;
import com.ycy.temperature.view.base.BaseActivity;
import com.ycy.temperature.view.view.TitleView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by MI on 2018/7/18.
 */

public class IdentityActivity extends BaseActivity {
    @BindView(R.id.title)
    TitleView title;
    public static final int REQUEST_CODE_SELECT = 1000;
    public static final int REQUEST_SELECT = 2000;
    /**
     * 获取读写权限code
     */
    private static final int REQUEST_CODE_STORAGE = 300;
    @BindView(R.id.Image_Positive)
    ImageView ImagePositive;
    @BindView(R.id.Image_Opposite)
    ImageView ImageOpposite;
    @BindView(R.id.Text_Submission)
    TextView TextSubmission;
    private int maxImgCount = 4;
    Intent ImageIntent;
    String StrPositive = "";
    String StrOpposite = "";
    Intent intent = null;
    String mobile = "";
    String password = "";
    @Override
    protected int getLayout() {
        return R.layout.activity_identity;
    }

    @Override
    protected void setData() {

    }

    @Override
    protected void init(Bundle inBundle) {
        ButterKnife.bind(this);
        QMUIStatusBarHelper.setStatusBarLightMode(this);

        title.getLeft_ibtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        intent = getIntent();
        mobile = intent.getStringExtra("mobile");
        password = intent.getStringExtra("password");
        ImageIntent = new Intent(IdentityActivity.this, ImageGridActivity.class);
        initImagePicker();
    }

    @OnClick({R.id.Image_Positive, R.id.Image_Opposite, R.id.Text_Submission})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.Image_Positive:
                this.ImageIntent.putExtra(ImageGridActivity.KEY_IMAGE_SIZE, 1);
                startActivityForResult(ImageIntent, REQUEST_CODE_SELECT);
                break;
            case R.id.Image_Opposite:
                this.ImageIntent.putExtra(ImageGridActivity.KEY_IMAGE_SIZE, 1);
                startActivityForResult(ImageIntent, REQUEST_SELECT);
                break;
            case R.id.Text_Submission:
                Intent intent = new Intent(IdentityActivity.this, InformationActivity.class);
                intent.putExtra("mobile", mobile);
                intent.putExtra("password", password);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //添加图片返回
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                if (images != null) {
                    getPermission(images, requestCode);
                    Glide.with(IdentityActivity.this).load(images.get(0).img_name).into(ImagePositive);
                }
            } else if (data != null && requestCode == REQUEST_SELECT) {
                if (images != null) {
                    getPermission(images, requestCode);
                    Glide.with(IdentityActivity.this).load(images.get(0).img_name).into(ImageOpposite);
                }
            }
        }
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(100);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(100);                         //保存文件的高度。单位像素
    }

    /**
     * 获取读写权限
     */
    private void getPermission(final List<ImageItem> list, final int type) {

        AndPermission.with(this)
                .requestCode(REQUEST_CODE_STORAGE)
                .permission(Permission.STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        compressionImagesList(list, type);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

                    }
                })
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {

                    }
                }).start();
    }

    private void compressionImagesList(final List<ImageItem> list, final int type) {
        List<String> paths = new ArrayList<>();
        final List<File> fileList = new ArrayList<>();
        for (ImageItem imageItem : list) {
            paths.add(imageItem.img_name);
        }
        Luban.with(this)
                .load(paths)                                   // 传人要压缩的图片列表
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
                .setTargetDir(getPath())                        // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        fileList.add(file);
                        if (fileList.size() == list.size()) {
                            upLoadImage(fileList, type);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩

    }

    public void upLoadImage(List<File> self_imgs, int type) {
        if (type == REQUEST_CODE_SELECT) {
            UserNetWorks.getPositive(self_imgs, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.i("response111", e.getMessage().toString());
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i("response111", response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject jsonObject2 = new JSONObject(jsonObject.getString("data"));
                        StrPositive = jsonObject2.getString("frontPath");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else if (type == REQUEST_SELECT) {
            UserNetWorks.getOpposite(self_imgs, new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    Log.i("response111", e.getMessage().toString());
                }

                @Override
                public void onResponse(String response, int id) {
                    Log.i("response111", response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject jsonObject2 = new JSONObject(jsonObject.getString("data"));
                        StrOpposite = jsonObject2.getString("frontPath");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

    }

    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/temperature/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }
}
